<?php
require_once 'auth.php';
requireLogin();
$message =$item_id=$quantity='';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = dbConnect();
    $item_id = $_POST['item_id'];
    $quantity = $_POST['quantity'];

    // 开始事务
    $conn->begin_transaction();

    try {
        $stmt = $conn->prepare('INSERT INTO stock_records (item_id, quantity, operation_type, operator_id) VALUES (?, ?, "out", ?)');
        $stmt->bind_param('iii', $_POST['item_id'], $_POST['quantity'], $_SESSION['user_id']);
        $stmt->execute();

        // 更新库存数量
        $updateStmt = $conn->prepare('UPDATE inventory SET quantity = quantity - ? WHERE id = ?');
        $updateStmt->bind_param('ii', $_POST['quantity'], $_POST['item_id']);
        $updateStmt->execute();

        // 记录操作日志
        $logStmt = $conn->prepare("INSERT INTO operation_logs (user_id, operation_type, target_id, details) VALUES (?, 'out', ?, ?)");
        $logDetails = '出库数量：' . $_POST['quantity'];
        $logStmt->bind_param('iis', $_SESSION['user_id'], $_POST['item_id'], $logDetails);
        $logStmt->execute();

        // 提交事务
        $conn->commit();
        // 显示成功消息
        $message= "出库成功";
    } catch (Exception $e) {
        // 回滚事务
        $conn->rollback();
        // 可以在这里添加错误处理逻辑，例如显示错误信息
        $message= "出库失败: ";
        //echo "操作失败: " . $e->getMessage();
    }
}

// 获取物品列表
$conn = dbConnect();
$items = $conn->query('SELECT id, product_name,quantity FROM inventory');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>出库管理</title>
    <link rel="stylesheet" href="/dist/css/tabler.min.css">
</head>
<body class="layout-fluid layout-vertical">
    <?php include 'navbar.php'; ?>
    <div class="page">
        <div class="container-fluid">
            <div class="card mt-3">
                <div class="card-header">
                    <h3 class="card-title">货物出库</h3>
                </div>
                <form method="post">
                    <div class="card-body">
                        <div class="mb-3">
                        <?php if (!empty($message)): ?>
                                <div class="alert alert-success" role="alert">
                                    <div class="alert-icon">
                                        <!-- Download SVG icon from http://tabler.io/icons/icon/check -->
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"
                                            viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                                            stroke-linecap="round" stroke-linejoin="round"
                                            class="icon alert-icon icon-2">
                                            <path d="M5 12l5 5l10 -10" />
                                        </svg>
                                    </div>
                                    <div>
                                        <h4 class="alert-heading">Wow! Everything worked!</h4>
                                        <div class="alert-description">
                                            <?= htmlspecialchars($message) ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">选择物品</label>
                            <select name="item_id" class="form-select" id="item_id" required>
                                <?php while($item = $items->fetch_assoc()): 
                                    $selected = ($item['id'] == $item_id)? 'selected' : '';
                                    ?>
                                    <option value="<?= $item['id'] ?>" data-quantity="<?= htmlspecialchars($item['quantity']) ?>" <?=$selected?>>商品名称 <?= htmlspecialchars($item['product_name']) ?> 当前库存：<?= htmlspecialchars($item['quantity']) ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">出库数量</label>
                            <input type="number" name="quantity" class="form-control" min="1" id="quantity" value="<?=$quantity?>" required>
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">提交出库</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="/dist/js/tabler.min.js"></script>
</body>
</html>
<script>
    document.getElementById('item_id').addEventListener('change', function() {
        var selectedOption = this.options[this.selectedIndex];
        var maxQuantity = selectedOption.getAttribute('data-quantity');
        document.getElementById('quantity').setAttribute('max', maxQuantity);
    });
</script>